@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());
  }
  protected static void cleanStorageAccount(String storageAccountName) {
    OperationResponse operationResponse = null;
    try {
      operationResponse =
          storageManagementClient.getStorageAccountsOperations().delete(storageAccountName);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ServiceException e) {
      e.printStackTrace();
    }

    if (operationResponse != null) {
      Assert.assertEquals(200, operationResponse.getStatusCode());
    }
  }
  @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 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 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());
  }
  /**
   * 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<String, Object> tracingParameters = new HashMap<String, Object>();
      CloudTracing.enter(invocationId, this, "listFamiliesAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
      url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operatingsystemfamilies";
    String baseUrl = this.getClient().getBaseUri().toString();
    // 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;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2015-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
      if (statusCode == HttpStatus.SC_OK) {
        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();
      }
    }
  }